// zoo.cpp
#include "animal.hpp"
#include <arpa/inet.h>
#include <cstring>
#include <dlfcn.h>
#include <iostream>
#include <ostream>
#include <sys/socket.h>
#include <unistd.h>

void handle_connection(int sock) {
  char buffer[1024] = {0};
  read(sock, buffer, 1024);

  // 解析消息
  char *type = strtok(buffer, " ");
  char *name = strtok(nullptr, " ");

  // 动态加载库
  std::string so_path = std::string("../lib/") + type + ".so";
  void *handle = dlopen(so_path.c_str(), RTLD_LAZY);
  if (!handle) {
    std::cerr << "Error loading library: " << dlerror() << std::endl;
    return;
  }

  // 获取创建函数
  auto create = (create_t)dlsym(handle, "create");
  auto destroy = (destroy_t)dlsym(handle, "destroy");

  if (Animal *animal = create()) {
    std::cout << "Created " << name << ": ";
    animal->sound();
    destroy(animal);
  }

  dlclose(handle);
}

int main() {
  int server_fd = socket(AF_INET, SOCK_STREAM, 0);
  sockaddr_in address;
  address.sin_family = AF_INET;
  address.sin_addr.s_addr = INADDR_ANY;
  address.sin_port = htons(8080);

  if (bind(server_fd, (sockaddr *)&address, sizeof(address)) < 0) {
    std::cerr << "Bind failed: " << strerror(errno) << std::endl;
    close(server_fd);
    return -1;
  }
  listen(server_fd, 5);

  while (true) {
    int new_socket = accept(server_fd, nullptr, nullptr);
    handle_connection(new_socket);
    close(new_socket);
  }
  return 0;
}